package cn.shujuhai.qtadmin.platform.pluging.xss;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang3.StringUtils;

import cn.shujuhai.qtadmin.platform.kit.JsoupUtil;

/**
 * @author dch
 */
public class XssRequest extends HttpServletRequestWrapper {

    public static final String CONTENT = "content";
    public static final String WITH_HTML = "WithHtml";
    final HttpServletRequest orgRequest;
    private final boolean isIncludeRichText;

    public XssRequest(HttpServletRequest request, boolean isIncludeRichText) {
        super(request);
        orgRequest = request;
        this.isIncludeRichText = isIncludeRichText;
    }

    public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
        if (req instanceof XssRequest) {
            var request = (XssRequest)req;
            return request.getOrgRequest();
        }
        return req;
    }

    @Override
    public String getParameter(String name) {
        var flag = CONTENT.equals(name) || name.endsWith(WITH_HTML);
        if (flag && !isIncludeRichText) {
            return super.getParameter(name);
        }
        name = JsoupUtil.clean(name);
        String value = super.getParameter(name);
        if (StringUtils.isNotBlank(value)) {
            value = JsoupUtil.clean(value);
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] arr = super.getParameterValues(name);
        if (arr != null) {
            for (int i = 0; i < arr.length; i++) {
                arr[i] = JsoupUtil.clean(arr[i]);
            }
        }
        return arr;
    }

    @Override
    public String getHeader(String name) {
        name = JsoupUtil.clean(name);
        String value = super.getHeader(name);
        if (StringUtils.isNotBlank(value)) {
            value = JsoupUtil.clean(value);
        }
        return value;
    }

    public HttpServletRequest getOrgRequest() {
        return orgRequest;
    }
}
